using McpApi.Services;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// 配置Serilog
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .WriteTo.Console()
    .WriteTo.File("logs/mcpapi-.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

builder.Host.UseSerilog();

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "MES MCP API", Version = "v1" });
});

// 注册MCP服务
builder.Services.AddScoped<MCPProtocolHandler>();
builder.Services.AddSingleton<IToolRegistry, ToolRegistry>();
builder.Services.AddScoped<MESToolService>();
builder.Services.AddScoped<WeatherService>();
builder.Services.AddScoped<WeatherImpactAnalysisService>();
builder.Services.AddHttpClient<MESToolService>();
builder.Services.AddHttpClient<WeatherService>();

// 注册工具初始化服务
builder.Services.AddHostedService<ToolInitializationService>();

// 配置CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "MES MCP API v1");
        c.RoutePrefix = string.Empty; // 设置Swagger UI为根路径
    });
}

app.UseSerilogRequestLogging();

app.UseCors("AllowAll");

app.UseAuthorization();

app.MapControllers();

// 添加根路径重定向到Swagger
app.MapGet("/", () => Results.Redirect("/swagger"));

Log.Information("MES MCP Server 启动完成");

app.Run();
